package com.bp.hearthealth.pulse.lnapps.bp_view

import android.animation.Animator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.bp_extension.dp2px
import com.bp.hearthealth.pulse.lnapps.bp_itfc.OnBpCountdownListener
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants


/**
 * @author isnoam
 * @package_name CountdownCircleView
 * @description：
 */
class BPCountdownCircleView : View {
    private var time: Long = 0L
    private var layerId: Int = 0
    private lateinit var rectF: RectF
    private lateinit var canvas: Canvas
    private var radius: Double = 0.0
    private var viewHeight: Int = 0
    private var viewWidth: Int = 0
    private var drawNumber: Int = 0

    private var circleColor = Color.GRAY
    private var progressColor = Color.RED
    private var textColor = Color.BLACK
    private var circlePaint: Paint? = null//圆环
    private var progressPaint: Paint? = null//进度条
    private var backgroundPaint: Paint? = null//背景
    private var totalTime: Long = 0 // 默认倒计时时间
    private var currentTime: Long = 0
    private val SWEEP_ANGLE = 360 // 弧形的总角度
    private var animator: ValueAnimator? = null
    private var currentSweepAngle = 1
    private var lastCurrentSweepAngle = 0
    private var countdownListener: OnBpCountdownListener? = null

    private var handler: Handler = Handler(Looper.getMainLooper())
    private var number = 0 //倒计时执行次数
    private var isPaused = false // 标记是否暂停
    private var isAnimationEnd = false


    constructor(context: Context?) : super(context) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        initAttrs(attrs)
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context, attrs, defStyleAttr
    ) {
        initAttrs(attrs)
        init()
    }

    private fun initAttrs(attrs: AttributeSet?) {
        if (attrs != null) {
            // 获取自定义属性
            val context = context
            val typedArray = context.obtainStyledAttributes(attrs, R.styleable.CountdownCircleView)
            circleColor =
                typedArray.getColor(R.styleable.CountdownCircleView_circleColor, Color.GRAY)
            progressColor =
                typedArray.getColor(R.styleable.CountdownCircleView_progressColor, Color.BLUE)
            textColor = typedArray.getColor(R.styleable.CountdownCircleView_textColor, Color.BLACK)
            typedArray.recycle()
        }
    }

    private fun init() {
        //圆环
        circlePaint = Paint()
        circlePaint!!.color = circleColor
        circlePaint!!.style = Paint.Style.STROKE
        circlePaint!!.strokeWidth = dp2px(26f).toFloat()
        circlePaint!!.isAntiAlias = true

        //进度条
        progressPaint = Paint()
        progressPaint!!.color = progressColor
        progressPaint!!.style = Paint.Style.STROKE
        progressPaint!!.strokeWidth = dp2px(26f).toFloat()
        progressPaint!!.isAntiAlias = true
        progressPaint!!.strokeCap = Paint.Cap.ROUND
        progressPaint!!.isDither = true
    }

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        this.canvas = canvas
        viewWidth = width
        viewHeight = height
        radius = viewWidth.coerceAtMost(viewHeight) / 2.5
        rectF = RectF(
            (viewWidth / 2 - radius).toFloat(),
            (viewHeight / 2 - radius).toFloat(),
            (viewWidth / 2 + radius).toFloat(),
            (viewHeight / 2 + radius).toFloat()
        )
        //绘制整个圆环
        canvas.drawCircle(
            (viewWidth / 2).toFloat(), (viewHeight / 2).toFloat(), radius.toFloat(), circlePaint!!
        )
        canvas.drawArc(rectF, -90f, 1.toFloat(), false, progressPaint!!)
        // 绘制倒计时进度
        if (!isAnimationEnd && currentSweepAngle != 0) {
            canvas.drawArc(rectF, -90f, currentSweepAngle.toFloat(), false, progressPaint!!)
        }
    }


    private val runnable = object : Runnable {
        override fun run() {
            if (!isPaused) {
                if (currentTime > 0) {
                    time = Constants.HEART_RATE_TIME - currentTime
                    handleCountdownProgress(time.toInt())
                    currentTime -= 1000
                    handler.postDelayed(this, 1000)
                } else {
                    if (currentTime == 0.toLong()) {
                        handleCountdownFinished(++number)
                    }
                }
            }
        }
    }

    // 暂停倒计时
    fun pauseCountdown() {
        isPaused = true
        currentSweepAngle = 1 // 设置为初始值
        invalidate() // 重新绘制视图
        cancelMessage()
    }

    // 继续倒计时
    fun resumeCountdown() {
        isPaused = false
        startProgressAnimation(currentTime) // 继续倒计时
    }

    fun startProgressAnimation(duration: Long) {
        drawNumber = 0
        isPaused = false
        currentTime = duration
        isAnimationEnd = false // 重置动画结束标志
        if (animator == null) {
            animator = ValueAnimator.ofInt(0, SWEEP_ANGLE)
            animator!!.interpolator = LinearInterpolator()
            animator!!.addUpdateListener { animation ->
                if (!isAnimationEnd) {
                    currentSweepAngle = animation.animatedValue as Int
                    invalidate() // 刷新View
                }
            }
            animator!!.addListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animation: Animator) {

                }

                override fun onAnimationEnd(animation: Animator) {
                    isAnimationEnd = true // 动画结束时设置标志
                }

                override fun onAnimationCancel(animation: Animator) {

                }

                override fun onAnimationRepeat(animation: Animator) {

                }
            })
        }
        if (animator!!.isRunning) {
            animator!!.cancel()
        }
        animator!!.duration = currentTime
        // 在开始动画之前重置 currentSweepAngle 为 0
        currentSweepAngle = 0

        animator!!.start()
        handler.removeCallbacksAndMessages(null)
        handler.post(runnable)
    }

    fun setOnCountdownListener(listener: OnBpCountdownListener?) {
        this.countdownListener = listener
    }

    private fun handleCountdownFinished(number: Int) {
        // 在倒计时结束时调用该方法，以触发接口回调
        if (countdownListener != null) {
            countdownListener!!.onCountdownFinished(number)
        }
    }

    private fun handleCountdownProgress(number: Int) {
        // 在倒计时结束时调用该方法，以触发接口回调
        if (countdownListener != null) {
            countdownListener!!.onCountdownProgress(number)
        }
    }

    fun cancelMessage(vararg removeListener:Boolean) {
        animator?.cancel()
        handler.removeCallbacksAndMessages(null)
        isAnimationEnd = true // 取消时设置动画结束标志
        if (removeListener.isNotEmpty()){
            countdownListener = null
        }
    }
}
